import React, { useState, useEffect } from 'react';
import Square from './Square';
import Timer from './Timer';

const colors = ["red", "blue", "green", "yellow", "pink", "purple"];

const generateSquares = (count: number) => {
    const pairsCount = count / 2;
    const colorsToUse = colors.slice(0, pairsCount);
    const squares: string[] = [];

    colorsToUse.forEach(color => {
        squares.push(color);
        squares.push(color);
    });

    for (let i = squares.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [squares[i], squares[j]] = [squares[j], squares[i]];
    }

    return squares;
};

const GameBoard: React.FC = () => {
    const [mode, setMode] = useState<'easy' | 'hard'>('easy');
    const squareCount = mode === 'easy' ? 8 : 16;
    const [squares, setSquares] = useState(generateSquares(squareCount));
    const [pairsFound, setPairsFound] = useState<number[]>([]);
    const [selectedSquares, setSelectedSquares] = useState<number[]>([]);
    const [borderIndex, setBorderIndex] = useState<number | null>(null);
    const [gameWon, setGameWon] = useState(false);
    const [timerKey, setTimerKey] = useState(0); // 新增状态以控制计时器的重置

    const handleSquareClick = (index: number) => {
        if (pairsFound.includes(index) || selectedSquares.length === 2 || selectedSquares.includes(index)) {
            return;
        }

        if (selectedSquares.length === 1) {
            const firstIndex = selectedSquares[0];

            if (squares[firstIndex] === squares[index]) {
                setPairsFound(prev => [...prev, firstIndex, index]);
            }
            setBorderIndex(null);
            setSelectedSquares([]);
        } else {
            setSelectedSquares([index]);
            setBorderIndex(index);
        }
    };

    useEffect(() => {
        if (pairsFound.length === squares.length) {
            setGameWon(true);
        }
    }, [pairsFound, squares.length]);

    const handleTimeout = () => {
        alert('时间到，游戏结束!');
    };

    const handleModeChange = (newMode: 'easy' | 'hard') => {
        setMode(newMode);
        setPairsFound([]);
        setSelectedSquares([]);
        setBorderIndex(null);
        setGameWon(false);
        setSquares(generateSquares(newMode === 'easy' ? 8 : 16));
        setTimerKey(prev => prev + 1); // 重置计时器的关键，以强制重新渲染计时器
    };

    return (
        <div>
            <Timer duration={180} onTimeout={handleTimeout} key={timerKey} />
            <div>
                <button onClick={() => handleModeChange('easy')}>简易版</button>
                <button onClick={() => handleModeChange('hard')}>复杂版</button>
            </div>
            {gameWon ? (
                <div style={{ fontSize: '24px', color: 'green', margin: '20px' }}>
                    游戏成功！你找到了所有的配对！ 🎉
                </div>
            ) : (
                <div style={{ display: 'flex', flexWrap: 'wrap', maxWidth: '300px' }}>
                    {squares.map((color, index) => (
                        <Square
                            key={index}
                            color={color}
                            onClick={() => handleSquareClick(index)}
                            visible={!pairsFound.includes(index)}
                            borderStyle={borderIndex === index || (selectedSquares.length === 1 && selectedSquares[0] === index)}
                        />
                    ))}
                </div>
            )}
        </div>
    );
};

export default GameBoard;
